package br.ufpe.cin.wormbox.core;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.LinkedList;

import br.ufpe.cin.wormbox.protocolo.RPFTPacket;
import br.ufpe.cin.wormbox.protocolo.RPFTServer;
import br.ufpe.cin.wormbox.protocolo.RPFTSocket;

public class FachadaServidor {

	private ServerSocket TCPS;
	private LinkedList<ThreadCliente> listaThreads;
	public Servidor server;
	
	public FachadaServidor() throws IOException {
		this.server = new Servidor();
		this.TCPS = new ServerSocket(5000);
		this.listaThreads = new LinkedList<ThreadCliente>();
	}
	
	@Override
	public void finalize() throws Throwable {
		this.server.finalize();
		super.finalize();
	}
	
	public ArrayList<DadosUsuario> getUsers() {
		return new ArrayList<DadosUsuario>(this.server.conjuntoUsers.values());
	}
	
	public void rodar() throws IOException {
		Socket s;
		
		while(true) {
			System.out.println("Esperando conexao...");
			s = this.TCPS.accept();
			System.out.println("Conexao aceita!");
			
			ThreadCliente t = new ThreadCliente(s, this);
			this.listaThreads.add(t);
			t.start();
		}
	}
	
	public void removerThread(ThreadCliente t) {
		this.listaThreads.remove(t);
		
		System.out.println("\nnova lista:");
		for(ThreadCliente t1 : listaThreads) {
			System.out.println(t1.IP);
		}
	}
	
	public LinkedList<ThreadCliente> getClientes() {
		return this.listaThreads;
	}
}
